﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OZ_ReportPostingsCreateInterfaceBusiness : OZInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption OZ_Query { get; set; }

        //店铺ID
        public string SellerId { get; set; }
        public OZ_ReportPostingsCreateInterfaceBusiness()
        {
            this.InterfaceName = "发货报告_店铺1";
            //索引字段
            this.MapFields = GetMapField("OZ_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            OZ_Query = this.interfaceOption.Where(x => x.OperateType == "OZ_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, OZ_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            try
            {
                //同一个seller_id授权的店铺任取一个sid请求报表数据即可
                //queryEventArgs.CustomData = sellerInterfaceBusiness.Query<Seller>(sellerInterfaceBusiness.LX_Query, SqlDb);
                //设置请求头参数
                var key = JObject.Parse(OZ_Query.TargetLoginData);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Client-Id", key["Client-Id"].Value<string>());
                headers.Add("Api-Key", key["Api-Key"].Value<string>());
                this.SellerId = key["Client-Id"].Value<string>();
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.SourceField == "processed_at_from").First().Notes.ToInt();
                queryEventArgs.CustomData = "fbs";
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            //获取请求的数据
            OZ_ReqDTO data = new OZ_ReqDTO();
            data.filter = new OZ_Filter();
            var to = DateTime.UtcNow.ToString("yyyy-MM-ddT HH:mm:ss.000Z").Replace(" ", "");
            var from = DateTime.UtcNow.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd") + "T16:00:00.000Z";
            //var from = DateTime.UtcNow.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-ddT HH:mm:ss.000Z").Replace(" ", "");
            data.filter.processed_at_from = from;
            data.filter.processed_at_to = to;
            data.filter.delivery_schema = new List<string>() { queryEventArgs.CustomData.ToString() };
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                ReportCodeDTO result = (ReportCodeDTO)JsonConvert.DeserializeObject<ReportCodeDTO>(queryEventArgs.ResultStr);
                if (!result.result.code.IsNullOrEmpty())
                {
                    //需要查询fbs和fbo两种物流方式的单据
                    if (queryEventArgs.CustomData.ToString() == "fbs")
                    {
                        queryEventArgs.CustomData = "fbo";
                    }
                    else
                    {
                        queryEventArgs.Page.Complete = true;
                    }
                    queryEventArgs.Success = true;
                    List<string> code = new List<string>();
                    code.Add(result.result.code);
                    queryEventArgs.Rows = code;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public List<ReportPostingsCreate> ExecuteInterface()
        {
            List<ReportPostingsCreate> report = new List<ReportPostingsCreate>();
            try
            {
                //获取报表代码
                List<string> code = this.Query<string>(this.OZ_Query, SqlDb);
                List<string> tableRows = new List<string>();
                List<string> title_FBS = new List<string>();
                List<string> title_FBO = new List<string>();
                HttpClient httpClient = new HttpClient();
                string LogType = "";
                var OZ_ReportInfo = new OZ_ReportInfoInterfaceBusiness();
                foreach (var item1 in code)
                {
                    //获取报表文件URL
                    string fileURL = OZ_ReportInfo.ExecuteInterface(item1);
                    httpClient.Url = fileURL;
                    //var e = httpClient.FileRequestExecl("");
                    string table = httpClient.FileRequestText();
                    //将请求的文本根据规则转换成数据列表
                    List<string> tableRows_ = table.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).ToList();
                    List<string> title_ = tableRows_[0].Split(';').ToList();
                    title_.Add("LogType");
                    tableRows_.RemoveAt(0);

                    if (title_FBS.Count == 0)
                    {
                        //添加表头
                        title_FBS.AddRange(title_);
                        LogType = ";FBS";
                    }
                    else
                    {
                        //添加表头
                        title_FBO.AddRange(title_);
                        LogType = ";FBO";
                    }
                    //将物流类型也加入到字段值中
                    for (int i = 0; i < tableRows_.Count; i++)
                    {
                        tableRows_[i] = tableRows_[i] + LogType;
                    }
                    tableRows.AddRange(tableRows_);
                }


                foreach (var item1 in tableRows)
                {
                    //var c = 1;
                    List<string> values = item1.Split(';').ToList();
                    Dictionary<string, string> keyValues = new Dictionary<string, string>();
                    if (item1.Contains(";FBS"))
                    {
                        keyValues = GetTableKeyValues(title_FBS, values);

                    }
                    else
                    {
                        keyValues = GetTableKeyValues(title_FBO, values);
                    }

                    if (keyValues.Count > 0)
                    {
                        ReportPostingsCreate row = new ReportPostingsCreate();
                        row.OrderNumber = keyValues.Keys.Contains("Order number") ? keyValues["Order number"] : ""; // values[0].Replace("\"", "");
                        row.ShipmentNumber = keyValues.Keys.Contains("Shipment number") ? keyValues["Shipment number"] : ""; //values[1].Replace("\"", "");
                        row.AcceptedForProcessing = keyValues.Keys.Contains("Accepted for processing") ? keyValues["Accepted for processing"] : "";// values[2].Replace("\"", "");
                        row.AcceptedForProcessing = row.AcceptedForProcessing.IsNullOrEmpty() ? "" : row.AcceptedForProcessing.ToDateTime().AddHours(8).ToString();//时间为俄罗斯时间转成中国时间
                        row.ShipmentDate = keyValues.Keys.Contains("Shipment date") ? keyValues["Shipment date"] : "";// values[3].Replace("\"", "");
                        row.ShipmentDate = row.ShipmentDate.IsNullOrEmpty() ? "" : row.ShipmentDate.ToDateTime().AddHours(8).ToString();//时间为俄罗斯时间转成中国时间
                        row.Status = keyValues.Keys.Contains("Status") ? keyValues["Status"] : "";// values[4].Replace("\"", "");
                        row.DeliveryDate = keyValues.Keys.Contains("Delivery date") ? keyValues["Delivery date"] : "";// values[5].Replace("\"", "");
                        row.DeliveryDate = row.DeliveryDate.IsNullOrEmpty() ? "" : row.DeliveryDate.ToDateTime().AddHours(8).ToString();//时间为俄罗斯时间转成中国时间
                        row.ActualDateOfHandingOverToDelivery = keyValues.Keys.Contains("Actual date of handing over to delivery") ? keyValues["Actual date of handing over to delivery"] : "";// values[6].Replace("\"", "");
                        row.ActualDateOfHandingOverToDelivery = row.ActualDateOfHandingOverToDelivery.IsNullOrEmpty() ? "" : row.ActualDateOfHandingOverToDelivery.ToDateTime().AddHours(8).ToString();//时间为俄罗斯时间转成中国时间
                        row.ShipmentAmount = keyValues.Keys.Contains("Shipment amount") ? keyValues["Shipment amount"] : "";// values[7].Replace("\"", "");
                        row.ShipmentCurrencyCode = keyValues.Keys.Contains("Shipment currency code") ? keyValues["Shipment currency code"] : "";// values[8].Replace("\"", "");
                        row.ProductName = keyValues.Keys.Contains("Product name") ? keyValues["Product name"] : "";// values[9].Replace("\"", "");
                        row.OZONId = keyValues.Keys.Contains("OZON id") ? keyValues["OZON id"] : "";// values[10].Replace("\"", "");
                        row.ArticleCode = keyValues.Keys.Contains("Article code") ? keyValues["Article code"] : "";// values[11].Replace("\"", "");
                        row.TotalProductCost = keyValues.Keys.Contains("Your price") ? keyValues["Your price"] : "";//values[12].Replace("\"", "");
                        row.ProductCurrencyCode = keyValues.Keys.Contains("Product currency code") ? keyValues["Product currency code"] : "";// values[13].Replace("\"", "");
                        row.ProductCostForCustomers = keyValues.Keys.Contains("Paid by the customer") ? keyValues["Paid by the customer"] : "";// values[14].Replace("\"", "");
                        row.CustomerCurrencyCode = keyValues.Keys.Contains("Customer currency code") ? keyValues["Customer currency code"] : ""; //values[15].Replace("\"", "");
                        row.Quantity = keyValues.Keys.Contains("Quantity") ? keyValues["Quantity"] : "";// values[16].Replace("\"", "");
                        row.DeliveryCost = keyValues.Keys.Contains("Delivery cost") ? keyValues["Delivery cost"] : "";// values[17].Replace("\"", "");
                        row.LinkedShipments = keyValues.Keys.Contains("Linked shipments") ? keyValues["Linked shipments"] : "";// values[18].Replace("\"", "");
                        row.RedemptionOfProducts = keyValues.Keys.Contains("Redemption of products") ? keyValues["Redemption of products"] : "";// values[19].Replace("\"", "");
                        row.ProductPriceBeforeDiscounts = keyValues.Keys.Contains("Product price before discounts") ? keyValues["Product price before discounts"] : "";// values[20].Replace("\"", "");
                        row.Discount = keyValues.Keys.Contains("Discount %") ? keyValues["Discount %"].Replace("%", "") : "";// values[21].Replace("\"", "").Replace("%", "");
                        row.DiscountRUB = keyValues.Keys.Contains("Discount RUB") ? keyValues["Discount RUB"] : ""; //values[22].Replace("\"", "");
                        row.Promotions = keyValues.Keys.Contains("Promotions") ? keyValues["Promotions"] : "";// values[23].Replace("\"", "");
                        row.FloorLift = keyValues.Keys.Contains("Floor lift") ? keyValues["Floor lift"] : "";// values[24].Replace("\"", "");
                        row.LogType = keyValues.Keys.Contains("LogType") ? keyValues["LogType"] : "";// values[25];
                        row.SellerId = this.SellerId;
                        row.id = row.ShipmentNumber + row.SellerId + row.LogType;
                        report.Add(row);
                    }
                }

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
            return report;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }


        public Dictionary<string, string> GetTableKeyValues(List<string> title, List<string> values)
        {
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            if (title.Count == values.Count)
            {
                for (int i = 0; i < title.Count; i++)
                {
                    keyValues.Add(title[i].Replace("\"", ""), values[i].Replace("\"", ""));
                }
            }

            return keyValues;
        }
    }

}